import 'dart:convert';
import 'dart:io';

class LanguageUtil {
  LanguageUtil._();

  // 默认简体中文路径
  static const String _zhPath = 'lib/l10n/intl_zh_Hans.arb';

  // 默认繁体中文路径
  static const _twPath = 'lib/l10n/intl_zh_Hant.arb';

  //goole翻译api
  static const _googleTranslationApi =
      'https://translation.googleapis.com/language/translate/v2';

  //google翻译api key
  static const _googleTranslationApiKey =
      'AIzaSyDVelcOaS31KDmYMBMcoE4ZkfReaUI8So4';

  static void translationZhHant() async {
    //如果_zhPath文件不存在 则不进行翻译
    final _zhPathFile = File(_zhPath);
    if (!_zhPathFile.existsSync()) {
      print('$_zhPath 文件不存在');
      return;
    }
    //读取文件json 内容
    String zhContent = _zhPathFile.readAsStringSync();
    //json文件转换
    Map<String, dynamic> zhMap = jsonDecode(zhContent);
    //zhMap 为空 则不进行翻译
    if (zhMap.isEmpty) {
      print('$_zhPath 文件内容为空');
      return;
    }
    final _twPathFile = File(_twPath);
    //如果_twPath文件不存在 则创建文件
    if (!_twPathFile.existsSync()) {
      _twPathFile.createSync();
    }
    //比对_zhPath文件内容和_twPath文件内容
    String twContent = _twPathFile.readAsStringSync();
    Map<String, dynamic> twMap = jsonDecode(twContent);
    //如果_twPath文件内容为空 则需要全部翻译
    Map<String, dynamic> needTranslationMap = {};
    if (twMap.isEmpty) {
      zhMap.forEach((key, value) {
        needTranslationMap[key] = value;
      });
    } else {
      zhMap.forEach((key, value) {
        if (twMap[key] == null) {
          needTranslationMap[key] = value;
        }
      });
    }
    //如果需要翻译的内容为空 则不进行翻译
    if (needTranslationMap.isEmpty) {
      print('$_zhPath 文件内容和$_twPath 文件内容一致');
      return;
    }
    //进行翻译
    print('开始翻译: ${needTranslationMap.length} 条数据');
    Map<String, dynamic> twResult = await translateToTraditionalChinese(
        needTranslationMap);
    print('翻译完成: ${twResult.length} 条数据');
    //合并翻译结果

    twMap.addAll(twResult);
    //写入文件
    _twPathFile.writeAsStringSync(_jsonEncodeFormat(twMap));
  }

  static Future<Map<String, dynamic>> translateToTraditionalChinese(
      Map<String, dynamic> needTranslationMap) async {
    Map<String, dynamic> result = {};
    List<Future> futures = [];
    needTranslationMap.forEach((key, value) {
      futures.add(_googleTranslate(key, value, result));
    });
    await Future.wait(futures);
    return result;
  }

  static Future<void> _googleTranslate(String key, String value, Map<String, dynamic> result) async {
    final url = '$_googleTranslationApi?key=$_googleTranslationApiKey';
    final data = {
      'q': value,
      'source': 'zh',
      'target': 'zh-TW',
      'format': 'text'
    };
    HttpClientRequest request = await HttpClient().postUrl(Uri.parse(url));
    request.headers.set('content-type', 'application/json');
    request.add(utf8.encode(jsonEncode(data)));
    HttpClientResponse response = await request.close();

    String contents = await response.transform(utf8.decoder).join();
    final jsonResponse = jsonDecode(contents);
    final translations = jsonResponse['data']['translations'];
    final translatedText = translations[0]['translatedText'];
    print('key: $key, value: $translatedText');
    result[key] = translatedText;
  }

  /**
   * 格式化json 写入
   */
  static String _jsonEncodeFormat(Map<String, dynamic> twMap) {
    StringBuffer buffer = StringBuffer();
    buffer.write('{\n');
    twMap.forEach((key, value) {
      value = value.toString().replaceAll('\\n', '\\\\n');
      value = value.toString().replaceAll('\n', '\\n');
      buffer.write('  "$key": "$value",\n');
    });
    String result = buffer.toString();
    if (result.endsWith(',\n')) {
      result = result.substring(0, result.length - 2) + '\n';
    }
    result += '}';
    return result;
  }
}
